/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.create;

import br.com.foxline.model.*;
import br.com.foxline.service.CorrectorService;
import br.com.foxline.service.GroupService;
import br.com.foxline.util.Msg;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author luciano
 */
@ManagedBean
@ViewScoped
public class ManagerCreateCorrector implements Serializable {

    @EJB
    private CorrectorService correctorService;
    @EJB
    private GroupService groupService;
    private Corrector corrector;
    private Users user;
    private String confirm;

    @PostConstruct
    public void init() {
        this.corrector = new Corrector();
        corrector.setAddress(new Address());
        corrector.getAddress().setCity(new City());
        this.user = new Users();
    }

    public void save() {
        try {
            if (verifyUser()) {
                throw new Exception();
            }
            this.corrector.setUser(user);
            correctorService.save(corrector);
            Msg.messagemInfo(Msg.SuccessFull);
            init();
        } catch (Exception e) {
            Msg.messagemError(Msg.Failure);
        }
    }

    public boolean verifyUser() throws Exception {
        boolean r = false;
        if (!this.user.getPassword().equals(confirm)) {
            confirm = "";
            r = true;
            Msg.messagemError("Senhas não são iguais.");
            throw new Exception();
        } else {
            Groups g = groupService.findGroupByName("Corretor");
            List<Groups> grupos = new ArrayList<Groups>();
            grupos.add(g);
            this.user.setGroups(grupos);
            this.user.setPost("Corretor");
            this.user.setName(this.corrector.getName());
            this.user.setPassword(Users.encryptPassword(user.getPassword()));
        }
        return r;
    }

    public Corrector getCorrector() {
        return corrector;
    }

    public void setCorrector(Corrector corrector) {
        this.corrector = corrector;
    }

    public String getConfirm() {
        return confirm;
    }

    public void setConfirm(String confirm) {
        this.confirm = confirm;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }
}
